package com.bricker.laboratorymanagement.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bricker.laboratorymanagement.business.entity.Message;
import com.bricker.laboratorymanagement.business.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    //获取未读消息列表
    @GetMapping
    public List<Message> getMessageBystatus(HttpServletRequest request){
        String token=request.getHeader("access_token");
        Long uId= Long.valueOf(JWT.decode(token).getAudience().get(0));
        String idString=","+uId+",";
        List<Message> messages =messageService.list(Wrappers.<Message>lambdaQuery().eq(Message::getDelFlag,"0")
                .eq(Message::getStatus,"0")
                .orderByDesc(Message::getCreatedTime));
        List<Message> list =null;
        if(CollectionUtils.isNotEmpty(messages)){
            list=messages.stream().filter(x->(","+x.getReceivers()+",").indexOf(idString)!=-1).collect(Collectors.toList());
        }
        return list;

    }

    //将选中标记为已读消息
    @PostMapping
    public void updateMessageState(@RequestBody String ids){
        List<Long> idList= JSONObject.parseArray(ids,Long.class);
        List<Message> messages =messageService.list(Wrappers.<Message>lambdaQuery().in(Message::getId,idList))
                                .stream().map(x->{ x.setStatus("1");return x; }).collect(Collectors.toList());
        messageService.updateBatchById(messages);
    }


}
